#!/usr/bin/env python
import io, sys
import datetime

sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding='utf-8')

from flask import Flask, Response
from flask import request
import requests
import logging
import json
import locale
#locale.setlocale(locale.LC_ALL,"en_US.UTF-8")

app = Flask(__name__)

console = logging.StreamHandler()
fmt = '%(asctime)s - %(filename)s:%(lineno)s - %(name)s - %(message)s'
formatter = logging.Formatter(fmt)
console.setFormatter(formatter)
log = logging.getLogger("flask_webhook_dingtalk")
log.addHandler(console)
log.setLevel(logging.DEBUG)

EXCLUDE_LIST = ['prometheus', 'endpoint']

def time_change(utc_time):
    time_list = utc_time.split(".", 1) 
    origin_date_str = time_list[0] + 'Z'
    utc_date = datetime.datetime.strptime(origin_date_str, "%Y-%m-%dT%H:%M:%SZ")
    local_date = utc_date + datetime.timedelta(hours=8)
    local_date_str = datetime.datetime.strftime(local_date ,'%Y-%m-%d %H:%M:%S')
    return local_date_str

@app.route('/')
def index():
    return 'Webhook Dingtalk by Billy https://blog.51cto.com/billy98'

@app.route('/dingtalk/send/',methods=['POST'])

def hander_session():

    profile_url = sys.argv[1]
    post_data = request.get_data()
    post_data = json.loads(post_data.decode("utf-8"))['alerts']
    post_data = post_data[0]
    messa_list = []
    time_cn = time_change(post_data['startsAt'])
    messa_list.append('### 报警类型: %s' % post_data['status'].upper())
    messa_list.append('**startsAt:** %s' % time_cn)
    for i in post_data['labels'].keys():
        if i in EXCLUDE_LIST:
            continue
        else:
            messa_list.append("**%s:** %s" % (i, post_data['labels'][i]))
    if 'message' in post_data.keys():
        messa_list.append('**Describe:** %s' % post_data['annotations']['message'])
    elif 'description' in post_data.keys():
        messa_list.append('**Describe:** %s' % post_data['annotations']['description'])
    elif 'summary' in post_data.keys():
        messa_list.append('**Describe:** %s' % post_data['annotations']['summary'])   

    messa = (' \\n\\n > '.join(messa_list))
    status = alert_data(messa, post_data['labels']['alertname'], profile_url )
    log.info(status)
    return status

def alert_data(data,title,profile_url):
    headers = {'Content-Type':'application/json'}
    send_data = '{"msgtype": "markdown","markdown": {"title": \"%s\" ,"text": \"%s\" }}' %(title,data)  # type: str
    send_data = send_data.encode('utf-8')
    reps = requests.post(url=profile_url, data=send_data, headers=headers)
    return reps.text

if __name__ == '__main__':
    app.debug = False
    app.run(host='0.0.0.0', port='8080')